<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/22
 * Time: 9:34
 */

namespace app\api\controller;


use app\admin\model\Config;
use app\common\controller\Base;
use think\Db;

class Applyhelp extends Base
{

    /**
     *
     * 申请帮扶接口
     *
    */
    public function applyHelp()
    {

        $data = input('post.');

        if(!$data){
            $this->result('','-1','请将信息填写完整','json',[]);
        }

        $userInfo = $this->check($data['token']);
        $user_id = $userInfo['uid'];

        $data['user_id'] = $user_id;
        $data['create_time'] = time();

        if(empty($data['id_code']) || empty($data['cardname'])){
            $this->result('','-1','身份证信息获取不完全','json',[]);
        }

        if($data['name'] != $data['cardname']){
            $this->result('','-1','填写姓名与身份证不符','json',[]);
        }
        $data['is_dang'] = 1;
        $wheres[] = ['card_id','=',$data['id_code']];
        $wheres[] = ['real_name','=',$data['cardname']];
        $partyMember = Db::name('party_member')->where($wheres)->count();
        if($partyMember == 0){
            $data['is_dang'] = 0;
        }
		
        if(isset($data['rudang_date'])){
            $rDate = explode('/',$data['rudang_date']);
            $cr = count($rDate);
            if(!isset($rDate[1])){
                $data['rudang_date'] = "";
            }else{
                if($rDate[1]){
                    if(isset($rDate[2])){
                        if(!$rDate[2]){
                            $data['rudang_date'] = $rDate[0]."/".$rDate[1]."/1";
                        }
                    }else{
                        $data['rudang_date'] = $rDate[0]."/1/1";
                    }
                }else{
                    if($rDate[0]){
                        $data['rudang_date'] = $rDate[0]."/1/1";
                    }else{
                        $data['rudang_date'] = "";
                    }
                }
            }
        }

        if(!empty($data['buchong'])){
            $imgId = "";
            $buchongArr = json_decode($data['buchong'],true);
            foreach ($buchongArr as $k => $v){
                $imgInfo = array(
                    'type' => 2,
                    'img' => $v,
                    'user_id' => $user_id,
                    'create_time' => time()
                );
                $id = Db::name('images')->insertGetId($imgInfo);
                $imgId .= $id.",";
            }
            $imgId = substr($imgId,0,strlen($imgId)-1);

            $data['buchong'] = $imgId;
        }

        if(!empty($data['id_img_up'])){
            $idImgInfo =   $imgInfo = array(
                'type' => 3,
                'img' => $data['id_img_up'],
                'user_id' => $user_id,
                'create_time' => time()
            );
            $id = Db::name('images')->insertGetId($idImgInfo);
            $data['id_img_up'] = $id;
        }

        if(!empty($data['id_img_down'])){
            $idImgInfo =   $imgInfo = array(
                'type' => 4,
                'img' => $data['id_img_down'],
                'user_id' => $user_id,
                'create_time' => time()
            );
            $id = Db::name('images')->insertGetId($idImgInfo);
            $data['id_img_down'] = $id;
        }
        unset($data['token']);
        $data['status'] = 1;

        $res = Db::name('help_list')->insertGetId($data);
        if($res){

            if($data['level'] == 1){

                $zCount = Db::name('member')->where(['zhibu'=>$data['zhibu']])->count();
                if($zCount){
                    $memberMap[] = ['zhibu','=',$data['zhibu']];
                }else{
                    $memberMap[] = ['danwei','=',$data['danwei']];
                }
                $memberMap[] = ['role_id','=',4];
                $memberList = Db::name('member')->where($memberMap)->field('id')->select();
                $memberArr = [];
                foreach ($memberList as $k=>$v){
                    array_push($memberArr,$v['id']);
                }
                if(count($memberArr) > 0){
                    $key = array_rand($memberArr,1);
                    $helpId = $memberArr[$key];
                }else{
                    $helpId = 0;
                }

                $updateHelp['help_id'] = $helpId;
                $updateHelp['pass_user'] = $helpId;
                Db::name('help_list')->where(['id' => $res])->update($updateHelp);
            }

            $this->result('','1','申请成功','json',[]);
        }else{
            $this->result('','-1','申请失败','json',[]);
        }

    }

    /**
    * 通用图片上传接口
    * @return mixed
    */
    public function upload()
    {

        $C = new Config();
        $configInfo = $C->config_cache();

        $ext = $configInfo['upload_image_ext'];
        $size = $configInfo['upload_image_size'];
        if($size <= 0){
            $size = 100000000;
        }
        $config = [
            'size' => $size,
            'ext'  => $ext
        ];

        $type = input('type');
        $file = $this->request->file('file');
        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads/images/'.$type);
        $save_path   = '/uploads/images/'.$type.'/';

        $info        = $file->validate($config)->move($upload_path);

        if ($info) {
            $result = [
                'url'   => str_replace('\\', '/', $save_path . $info->getSaveName())
            ];
            $this->result($result,'1','文件上传成功','json',[]);
        } else {
            $this->result('','-1',$file->getError(),'json',[]);
        }


    }

    /**
     * 图片上传接口(ios端)
     * @return mixed
     */
    public function uploadIos()
    {

//        $C = new Config();
//        $configInfo = $C->config_cache();
//
//        $ext = $configInfo['upload_image_ext'];
//        $size = $configInfo['upload_image_size'];
//        if($size <= 0){
//            $size = 2097152;
//        }
//        $config = [
//            'size' => $size,
//            'ext'  => $ext
//        ];

        $type = input('type');
        $response = array();
        $file = $this->request->file('file');

        // 文件类型限制  "file"名字必须和iOS客户端上传的name一致
        if ($_FILES["file"]["error"] > 0) {
            $response ["error"] = "错误代码".$_FILES["file"]["error"];
            echo json_encode($response);
        } else {
            //获取传入的文件名
            $fillName = $_FILES['file']['name'];
            //以 "." 为界对文件名分割，并存入数组
            $dotArray = explode('.', $fillName);
            //获取文件格式
            $type2 = end($dotArray);
            // - - - - -
            //小技巧:客户端传入的文件名，除了文件的格式要对之外，文件名部分是可以随意填写。
            //经过点分割后，就可以将文件名和文件格式分开，分开后下标为0的就是文件名，部分，这时候就间接实现了传参，获得用户的id
//            $userId = $dotArray[0];
            $name = date('YmdHis',time());
            // - - - -
            //设置存入的文件名（路径）
//            halt($userId);
            $path = "uploads/images/".$type;
            $info =$file->move($path);
            $uploadPath = str_replace('\\', '/', $path . '/' . $info->getSaveName());
//            halt($uploadPath);
//            $path = '/uploads/images/'.$type.'/';
            // 从临时目录复制到目标目录
//            move_uploaded_file($_FILES["file"]["tmp_name"],$path);
            //校验传入后文件是否存在
            if (file_exists($path)){
                $response ['success']= 1;
                $response ['url']= $uploadPath;
                $this->result($response,'1','文件上传成功','json',[]);
                //json格式返回
//                echo json_encode($response);
            }else {
                $response ['success'] = 0;
                $this->result('','-1','文件上传失败','json',[]);
//                echo json_encode($response);
            }

//        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads/images/'.$type);
//        $save_path   = '/uploads/images/'.$type.'/';
//        $info        = $file->validate($config)->move($upload_path);
//
//        if ($info) {
//            $result = [
//                'url'   => str_replace('\\', '/', $save_path . $info->getSaveName())
//            ];
//            $this->result($result,'1','文件上传成功','json',[]);
//        } else {
//            $this->result('','-1',$file->getError(),'json',[]);
        }


    }


    /**
     * 申请列表页面(目前只渲染地区的嵌套数组)
     * */
    public function index()
    {

        $pro = Db::name('pro')->field('id,value')->order("sort desc")->select();

        foreach ($pro as $k => $v ){

            $arr = Db::name('city')->where(['pid' => $v['id']])->field('id,value')->order("sort desc")->select();
            if(empty($arr)){
                $arr = [];
                $arr1 = [
                    'id' => 0,
                    'value' => '无'
                ];
                array_push($arr,$arr1);
            }
            $pro[$k]['city'] = $arr;

        }

        $data['address'] = $pro;

        $zhi = Db::name('zhibu')->select();
        $data['zhibu'] = $zhi;

        $this->result($data,'1','数据获取成功','json',[]);

    }


    /**
     * 获取支部信息
     * */
    public function getZhiBuList()
    {

        $id = input('id',1);
        if(!$id){
            $this->result([],'-1','数据获取有误','json',[]);
        }
        $where[] = ['pid','=',$id];
        $list = Db::name('zhibu_list')->where($where)->field('id,value')->select();

        $this->result($list,'1','数据获取成功','json',[]);

    }

}